package com.example.library.service;

import com.example.library.bean.BookDetail;
import com.example.library.bean.BorrowInfo;
import com.example.library.bean.model.Book;
import com.example.library.bean.model.BookType;
import com.example.library.bean.model.BorrowOrder;
import com.example.library.bean.model.FavoriteOrder;
import com.example.library.bean.response.Response;
import com.example.library.bean.response.SuccessResponse;
import com.example.library.dao.BookRepository;
import com.example.library.dao.BookTypeRepository;
import com.example.library.dao.BorrowOrderRepository;
import com.example.library.dao.FavoriteOrderRepository;
import com.example.library.util.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class BookService {

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private FavoriteOrderRepository favoriteOrderRepository;

    @Autowired
    private BorrowOrderRepository borrowOrderRepository;

    /**
     * 获取所有的书本
     * @return
     */
    public Response getAllBook() {
        List<Book> books = bookRepository.findAll();
        Response response = new SuccessResponse();
        response.setResult(books);
        return response;
    }

    /**
     * 根据类型查找书本
     * @param typeId
     * @return
     */
    public Response getBookByType(long typeId) {
        BookType bookType = new BookType();
        bookType.setTypeId(typeId);
        List<Book> books = bookRepository.findAllByType(bookType);
        Response response = new SuccessResponse();
        response.setResult(books);
        return response;
    }

    /**
     * 根据条件查找书本
     * @param condition
     * @return
     */
    public Response getBookByCondition(String condition) {
        List<Book> books = bookRepository.findAllByBookNameContainsOrAuthorContainsOrPublisherContains(condition,condition,condition);
        Response response = new SuccessResponse();
        response.setResult(books);
        return response;
    }



    /**
     * 获取书本详情
     * @return
     */
    public Response getBookDetail(long bookId,long userId) {
        Book book = bookRepository.findByBookId(bookId);
        FavoriteOrder order = favoriteOrderRepository.findByBook_BookIdAndUser_UserId(bookId,userId);
        BookDetail bookDetail = new BookDetail();
        bookDetail.setBook(book);
        bookDetail.setCollected(order != null);
        BorrowOrder borrowOrder = borrowOrderRepository.findByBook_BookIdAndUser_UserIdAndStatus(bookId,userId, Constant.NORMAL);
        if(borrowOrder != null) {
            bookDetail.setBorrowInfo(new BorrowInfo(borrowOrder.getBorrowDate(),borrowOrder.getReturnDeadline()));
        }else {
            bookDetail.setBorrowInfo(null);
        }
        Response response = new SuccessResponse();
        response.setResult(bookDetail);
        return response;
    }


}
